package com.zbl.zblproject.erp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.zbl.zblproject.core.entity.*;
import com.zbl.zblproject.core.mapper.*;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.erp.controller.ErpOrderController;
import com.zbl.zblproject.erp.entity.*;
import com.zbl.zblproject.erp.mapper.*;
import com.zbl.zblproject.erp.service.ErpGoodService;
import com.zbl.zblproject.erp.service.ErpOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/10
 * 出入库订单操作类
 */
@Service
public class ErpOrderServiceImpl implements ErpOrderService {

    @Value("${remote-url}")
    private String remoteUrl;

    @Autowired
    private ErpOweGoodsItemMapper erpOweGoodsItemMapper;

    @Autowired
    private ErpOrderMapper erpOrderMapper;

    @Autowired
    private ErpGoodMapper erpGoodMapper;

    @Autowired
    private ErpOrderItemMapper erpOrderItemMapper;

    @Autowired
    private ErpTempOrderItemMapper tempOrderItemMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ErpCategoryMapper erpCategoryMapper;


    @Autowired
    private ErpWarehouseItemMapper warehouseItemMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private SmallUnitMapper smallUnitMapper;

    @Autowired
    private ErpGoodService erpGoodService;

    @Autowired
    private ErpWarehouseMapper erpWarehouseMapper;

    @Autowired
    private ErpFinanceLogMapper erpFinanceLogMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private ErpRemoteOrderMapper erpRemoteOrderMapper;

    private static Logger logger = LoggerFactory.getLogger(ErpOrderService.class);


    @Override
    public boolean updateErpOrderByContext(String orderSn, String context) {
        ErpOrder order = getErpOrder(orderSn);
        if (order == null) {
            return false;
        }
        order.setContext(context);
        return erpOrderMapper.updateById(order) == 1;
    }

    @Override
    public ErpOrder getErpOrder(String orderSn) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", orderSn);
        ErpOrder order = erpOrderMapper.selectOne(wrapper);
        return order;
    }

    @Override
    @Transactional
    public ErpOrder createErpOrder(ErpOrder order, List<ErpOrderItem> items) {
        if (items.isEmpty()) {
            throw new RuntimeException("没有商品,创建失败!");
        }
        int goodsId = items.get(0).getGoodsId();
        String brandNames = Joiner.on(",").skipNulls().join(getItemsBrandName(items));
        /**
         * 订单判断,如果存在则删除以前所有的订单货位重新提交
         */
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", order.getOrderInfo());
        ErpOrder orderTemp = erpOrderMapper.selectOne(wrapper);
        logger.info("创建订单编号:{} 订单的状态:{}", order.getOrderInfo(), order.getStatus());
        if (orderTemp != null) {

            if (orderTemp.getStatus() == ErpOrderStatus.pass.getStatus()) {
                throw new RuntimeException("订单状态异常!");
            }

            QueryWrapper<ErpOrderItem> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("order_id", orderTemp.getOrderId());
            erpOrderItemMapper.delete(wrapper2);
            insertOrderItemByOrderId(items, orderTemp.getOrderId(), order.getOrderInfo());
            orderTemp.setStatus(order.getStatus());

            //更新订单的BrandName
            orderTemp.setBrandName(brandNames);

            orderTemp.setSupplierName(supplierMapper.selectSupplierNameByGoodsId(goodsId));
            erpOrderMapper.updateById(orderTemp);
            return orderTemp;
        } else {
            logger.info("订单mode:{}", order.getMode());

            //brandName设置
            order.setBrandName(brandNames);

            order.setSupplierName(supplierMapper.selectSupplierNameByGoodsId(goodsId));
            if (1 == erpOrderMapper.insert(order)) {
                insertOrderItemByOrderId(items, order.getOrderId(), order.getOrderInfo());
            } else {
                throw new RuntimeException("保存订单失败!");
            }
            return order;
        }
    }


    private Set<String> getItemsBrandName(List<ErpOrderItem> items) {
        if (items == null) {
            throw new NullPointerException("items is null");
        }
        Set<String> brands = new HashSet<>();
        for (ErpOrderItem item : items) {
            brands.add(brandMapper.selectBrandNameByGoodsId(item.getGoodsId()));
        }
        return brands;
    }

    /**
     * 将ErpOrderItem插入数据库
     *
     * @param items
     * @param orderId
     */
    @Override
    @Transactional
    public void insertOrderItemByOrderId(List<ErpOrderItem> items, int orderId, String orderSn) {
        items.forEach((x) -> {
            x.setOrderId(orderId);
            x.setGoodsName(erpGoodMapper.getGoodsNameByGoodsId(x.getGoodsId()));
            x.setBrandName(erpGoodMapper.getBrandNameByGoodsId(x.getGoodsId()));
            x.setOrderSn(orderSn);
            x.setSuppliersId(supplierMapper.selectSupplierIdByGoodsId(x.getGoodsId()));

            if (erpGoodMapper.checkGoodsCanUse(x.getGoodsId()) == 0) {
                erpOrderItemMapper.insert(x);
            } else {
                throw new RuntimeException(x.getGoodsName() + " 商品被禁用!");
            }
        });
    }

    @Override
    public List<ErpOrder> selectErpOrderByBrandName(String brandName, int mode, int status) {
        Integer id = brandMapper.selectIdByBrandName(brandName);
        Preconditions.checkNotNull(id, "没有发现对应品牌名的ID.");
        List<ErpOrder> orders = erpOrderMapper.selectErpOrdersByStatusAndModeAndBrandName(id, mode, status);
        return orders;
    }

    @Override
    @Transactional
    public boolean rollbackOrder(String orderInfo) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", orderInfo);
        ErpOrder order = erpOrderMapper.selectOne(wrapper);
        if (order == null) {
            throw new RuntimeException("无法查询到对应订单");
        }
        int status = order.getStatus();
        if (status == ErpOrderStatus.pass.getStatus()) {
            throw new RuntimeException("订单已完成无法回滚!");
        }
        if (status == ErpOrderStatus.financeFinish.getStatus()) {
            throw new RuntimeException("财务审核已完成无法回滚!");
        }
        if (status == ErpOrderStatus.finance.getStatus()) {
            if (1 == erpOrderMapper.updateOrderStatus(order.getOrderId(), ErpOrderStatus.submit.getStatus())) {
                //待财务审核回滚到审核中
                erpFinanceLogMapper.updateLogStatusByOrderSn(orderInfo, ErpOrderStatus.returnOrder.getStatus());
                return true;
            } else {
                throw new RuntimeException("订单更新失败!");
            }
        }
        if (status == ErpOrderStatus.submit.getStatus()) {
            if (1 == erpOrderMapper.updateOrderStatus(order.getOrderId(), ErpOrderStatus.draft.getStatus())) {
                return true;
            } else {
                throw new RuntimeException("订单更新失败!");
            }
        }
        return false;
    }


    @Override
    public List<ErpTempOrderItem> getOrderItemByOrder(String orderInfo) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", orderInfo);
        ErpOrder order = erpOrderMapper.selectOne(wrapper);
        if (order == null) {
            throw new RuntimeException("没有发现订单!");
        }
        List<ErpTempOrderItem> items = tempOrderItemMapper.listByOrderItem(order.getOrderId());
        items.forEach(x -> {
            ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
            x.setBrandName(brandMapper.selectById(goods.getBrandId()).getBrandName());
            x.setSupplier(supplierMapper.selectById(goods.getSuppliersId()));
            SmallUnit unit = smallUnitMapper.selectById(goods.getSmallunitId());
            if (unit != null) {
                x.setGoodsUnit(unit.getName());
            } else {
                x.setGoodsUnit("件");
            }
            Integer num = Optional.ofNullable(orderItemMapper.selectGoodsNumber(x.getOrderItemId())).orElse(0);
            x.setOriginGoodsNum(num);
            x.setGoodsSn(goods.getGoodsSn());
            x.setStock(goods.getGoodsNumber());
            x.setNumberUnit(String.valueOf(goods.getNumberUnit()));
        });
        return items;
    }

    @Override
    public List<ErpTempOrderItem> getOrderItemByOrderNotDesc(String orderInfo) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", orderInfo);
        ErpOrder order = erpOrderMapper.selectOne(wrapper);
        if (order == null) {
            throw new RuntimeException("没有发现订单!");
        }
        List<ErpTempOrderItem> items = tempOrderItemMapper.listByOrderItemNotDesc(order.getOrderId());
        items.forEach(x -> {
            ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
            x.setBrandName(brandMapper.selectById(goods.getBrandId()).getBrandName());
            x.setSupplier(supplierMapper.selectById(goods.getSuppliersId()));
            SmallUnit unit = smallUnitMapper.selectById(goods.getSmallunitId());
            if (unit != null) {
                x.setGoodsUnit(unit.getName());
            } else {
                x.setGoodsUnit("件");
            }
            Integer num = Optional.ofNullable(orderItemMapper.selectGoodsNumber(x.getOrderItemId())).orElse(0);
            x.setOriginGoodsNum(num);
            x.setGoodsSn(goods.getGoodsSn());
            x.setStock(goods.getGoodsNumber());
            x.setNumberUnit(String.valueOf(goods.getNumberUnit()));
        });
        return items;
    }


    @Override
    @Transactional
    public boolean deleteOrder(int id) {
        ErpOrder order = erpOrderMapper.selectById(id);
        if (order == null) {
            return false;
        }
        if (order.getStatus() == 3) {
            return false;
        }
        QueryWrapper<ErpOrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", order.getOrderId());
        erpOrderItemMapper.delete(wrapper);
        erpOrderMapper.deleteById(order.getOrderId());
        return true;
    }


    @Override
    public List<Order> getUserOrdersByNotDeliver(int deliver) {
        List<Order> orders = supplierOrdersByCanUse(deliver);
        return orders;
    }

    @Override
    public List<Order> getUserOrdersByIsConfirm(int deliver) {
        List<Order> orders = supplierOrdersByCanUseAndISConfirm(deliver);
        return orders;
    }

    @Override
    public List<Order> getOrdersByNotDeliver(int deliver, int mode) {
        Stopwatch watch = Stopwatch.createStarted();
        List<Order> orders;
        if (mode == 0) {

            orders = ordersByCanUse(deliver);
        } else {
            orders = supplierOrdersByCanUse(deliver);
        }
        watch.stop();
        logger.info("getOrdersByNotDeliver 耗时:{}", watch.toString());
        return orders;
    }

    @Override
    public List<Supplier> getSupplierByNotDeliver(int deliver, int mode) {

        List<Order> orders;
        if (mode == 0) {
            orders = ordersByCanUse(deliver);
        } else {
            orders = supplierOrdersByCanUse(deliver);
        }
        Map<String, Supplier> map = new HashMap<>();
        ErpTempOrderItem tempItem;
        for (Order order : orders) {
            for (ErpTempOrderItem item : order.getItems()) {
                Supplier supplier = item.getSupplier();
                if (map.containsKey(supplier.getSuppliersName())) {
                    supplier = map.get(supplier.getSuppliersName());
                    tempItem = item.cloneNew();
                    tempItem.setSupplier(null);
                    supplier.getItems().add(tempItem);
                } else {
                    Supplier newSupplier = supplier.cloneNew();
                    tempItem = item.cloneNew();
                    tempItem.setSupplier(null);
                    newSupplier.getItems().add(tempItem);
                    map.put(supplier.getSuppliersName(), newSupplier);
                }
            }
        }

        return Lists.newArrayList(map.values());
    }


    /**
     * 查询出所有的没有入库的订单
     *
     * @return
     */
    @Override
    public List<Order> ordersByCanUse(int deliver) {

        List<Order> orders = orderMapper.selectOrdersByCanUse(deliver);
        orders.forEach(x -> {
            x.setUser(adminUserMapper.selectById(x.getUserId()));
            x.setItems(getTempOrderByOrderSnAndNotInto(x.getOrderSn()));
            if (x.getItems().get(0).getSupplier()!=null){
                x.setSupplierName(x.getItems().get(0).getSupplier().getSuppliersName());
                x.setSupplierId(x.getItems().get(0).getSupplierId());//供应商主键
            }





        });
        //1.939 s -- 357.1 ms
        return orders;
    }

    @Override
    public List<Order> supplierOrdersByCanUseAndISConfirm(int deliver) {

        List<Order> result = orderMapper.selectStoreConfirmByDeliver(deliver);
        for (Order x : result) {
            x.setItems(getTempOrderByOrderSnAndNotOut(x.getOrderSn()));
            x.setSupplierName(x.getItems().get(0).getSupplier().getSuppliersName());
            x.setUser(adminUserMapper.selectUserById(x.getUserId()));
        }
        return result;
    }

    @Override
    public List<Order> supplierOrdersByCanUse(int deliver) {
//        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
//        orderWrapper.eq("is_pay", 1).eq("is_cancel", 0).eq("is_deliver", deliver).notLike("order_sn", "CGDD");
//        List<Order> orders = orderMapper.selectList(orderWrapper);
//        orders.forEach(x -> {
//            x.setUser(adminUserMapper.selectById(x.getUserId()));
//            x.setItems(getTempOrderByOrderSnAndNotOut(x.getOrderSn()));
//        });
//
//        return orders.stream().filter(x -> {
//            return !x.getItems().isEmpty();
//        }).collect(Collectors.toList());

        List<Order> orders = orderMapper.selectSupplierOrdersByCanUse(deliver);
        orders.forEach(x -> {
            x.setUser(adminUserMapper.selectById(x.getUserId()));
            x.setItems(getTempOrderByOrderSnAndNotOut(x.getOrderSn()));
        });
        return orders;
    }


    /**
     * 根据OrderSn来查询ErpTempOrderItem
     *
     * @param orderSn 订单的SN
     * @return
     */
    @Override
    public List<ErpTempOrderItem> getTempOrderByOrderSn(String orderSn) {
        QueryWrapper<OrderItem> itemWrapper = new QueryWrapper<>();
        itemWrapper.eq("order_sn", orderSn);
        List<OrderItem> list = orderItemMapper.selectList(itemWrapper);
        final List<ErpTempOrderItem> items = new ArrayList<>(list.size());
        list.forEach(x -> {
            items.add(orderItem2TempItem(x));
        });
        return items;
    }

    /**
     * 根据OrderSn来查询没有入库的ErpTempOrderItem
     *
     * @param orderSn
     * @return
     */
    @Override
    public List<ErpTempOrderItem> getTempOrderByOrderSnAndNotInto(String orderSn) {
//        QueryWrapper<OrderItem> itemWrapper = new QueryWrapper<>();
//        itemWrapper.eq("order_sn", orderSn).eq("is_into", 0);
//        List<OrderItem> list = orderItemMapper.selectList(itemWrapper);
//        final List<ErpTempOrderItem> items = new ArrayList<>(list.size());
//        list.forEach(x -> {
//            items.add(orderItem2TempItem(x));
//        });
//        return items;
        return orderItemMapper.selectErpTempOrderItemByOrderSnAndIsInto(orderSn, 0);
    }


    /**
     * 根据OrderSn来查询没有出库的ErpTempOrderItem
     *
     * @param orderSn
     * @return
     */
    @Override
    public List<ErpTempOrderItem> getTempOrderByOrderSnAndNotOut(String orderSn) {
//        QueryWrapper<OrderItem> itemWrapper = new QueryWrapper<>();
//        itemWrapper.eq("order_sn", orderSn).eq("is_out", 0);
//        List<OrderItem> list = orderItemMapper.selectList(itemWrapper);
//        final List<ErpTempOrderItem> items = new ArrayList<>(list.size());
//        list.forEach(x -> {
//           items.add(orderItem2TempItem(x));
//        });
//        return items;
        //if(orderItemMapper.selectOrderSnAndIsOutSum(orderSn,0 ) != 0) {
        return orderItemMapper.selectErpTempOrderItemByOrderSn(orderSn, 0);
//        }
//        return null;
    }


    /**
     * 根据OrderSn来查询ErpTempOrderItem
     *
     * @param orderSn 订单的SN
     * @return
     */
    @Override
    public List<ErpTempOrderItem> getTempOrderByOrderSnAndNotPurchasing(String orderSn) {
//        QueryWrapper<OrderItem> itemWrapper = new QueryWrapper<>();
//        itemWrapper.eq("order_sn", orderSn).eq("is_purchasing", "0");
//        List<OrderItem> list = orderItemMapper.selectList(itemWrapper);
//        final List<ErpTempOrderItem> items = new ArrayList<>(list.size());
//
//        list.forEach(x -> {
//            items.add(orderItem2TempItem(x));
//        });
//        return items;
        return orderItemMapper.selectErpTempOrderItemByOrderSnAndPurch(orderSn, 0);
    }

    @Override
    public ErpTempOrderItem orderItem2TempItem(OrderItem x) {
        ErpTempOrderItem orderItem = new ErpTempOrderItem();
        orderItem.setGoodsId(x.getGoodsId());
        orderItem.setGoodsList(0);
        orderItem.setGoodsListName("");
        orderItem.setGoodsName(x.getGoodsName());
        orderItem.setGoodsNum(x.getGoodsNum());
        orderItem.setGoodsPrice(x.getShopPrice());
        orderItem.setBrandName(x.getBrandName());
        orderItem.setOrderItemId(x.getId());
        orderItem.setGoodsDesc(x.getGoodsDesc());
        orderItem.setIsInto(x.getIsInto());

        ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
        String spe = "";
        if (goods != null) {
            spe = goods.getSpecifications();
            orderItem.setStock(goods.getGoodsNumber());
            orderItem.setPAddress(goods.getPAddress());
            orderItem.setSupplier(supplierMapper.selectById(goods.getSuppliersId()));
        } else {
            orderItem.setStock(0);
            orderItem.setPAddress("");
            orderItem.setSupplier(new Supplier());
        }
        orderItem.setNumberUnit(String.valueOf(goods.getNumberUnit()));
        orderItem.setSpecifications(spe);

        //brandMapper.selectCentralizedPurchasing(x.getSupplierName())
        Integer centralized = Optional.ofNullable(brandMapper.selectCentralizedPurchasing(x.getBrandName())).orElse(0);
        orderItem.setCentralizedPurchasing(centralized);
        orderItem.setDefaultWarehouse(erpWarehouseMapper.selectDefaultWarehouseByGoodsId(x.getGoodsId()));
        //小单位
        SmallUnit smallUnit = smallUnitMapper.selectById(goods.getSmallunitId());
        if (smallUnit == null) {
            orderItem.setGoodsUnit("件");
        } else {
            orderItem.setGoodsUnit(smallUnit.getName());
        }
        return orderItem;
    }

    @Override
    public IPage<ErpOrder> erpOrderList(String search, int current, int size) {

        Page page = new Page(current, size);
        IPage<ErpOrder> orders = erpOrderMapper.selectPageBySearch(page, search);
        orders.getRecords().forEach((x) -> {
            DecimalFormat df = new DecimalFormat("#0.00");
            x.setTotal(df.format(erpOrderMapper.selectOrderTotal(x.getOrderId())));
            x.setStoreName(adminUserMapper.selectNameById(x.getStoreId()));
        });
        return orders;
    }


    @Override
    @Transactional
    public ErpOrder passOrder(String orderInfo, int userId) {
        QueryWrapper<ErpOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info", orderInfo);
        final ErpOrder order = erpOrderMapper.selectOne(wrapper);
        if (order == null) {
            throw new RuntimeException("无法查询到对应订单");
        }
        int status = order.getStatus();

        if (order.getMode() == ErpOrderController.MODE_IN) {
            //调用入库步骤
            modeIn(order, status, userId);
        } else if (order.getMode() == ErpOrderController.MODE_OUT) {
            //调用出库步骤
            modeOut(order, status, userId);
            // modeOutOld(order, status, userId);
        } else if (order.getMode() == ErpOrderController.MODE_RETURN) {
            //退货单操作
            //todo 退货单流程未完成
        }
        if (erpOrderMapper.updateById(order) == 1) {
            return order;
        }
        throw new RuntimeException("订单更新失败!");
    }

    private void modeIn(final ErpOrder order, int status, int userId) {

        //入库单操作
        if (status == ErpOrderStatus.draft.getStatus()) {
            //草稿状态 -- 提交申请
            order.setStatus(ErpOrderStatus.submit.getStatus());

        } else if (status == ErpOrderStatus.finance.getStatus()) {
            //财务审核到 -- 订单审核
            throw new RuntimeException("入库单没有财务审核!");

        } else if (status == ErpOrderStatus.submit.getStatus()) {
            //状态由带审核变成审核成功
            AdminUser user = adminUserMapper.selectById(userId);
            Preconditions.checkNotNull(user, "用户不存在。");

            //提交申请 -- 通过
            //更新订单所有的数值
            QueryWrapper<ErpOrderItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.eq("order_id", order.getOrderId());
            List<ErpOrderItem> items = erpOrderItemMapper.selectList(itemWrapper);


            items.forEach((x) -> {
                ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
                if (goods != null) {
                    ErpWarehouseItem item = warehouseItemMapper.selectItemByGoodsIdAndWhId(x.getGoodsId(), x.getGoodsList());
                    logger.info("goods的ID:{} 名称:{} 数量:{} 待加数量:{} 缺货数量:{}",
                            goods.getGoodsId(), goods.getGoodsName(), goods.getGoodsNumber(), x.getGoodsNum(), x.getOweNum());
                    OrderItem orderItem = null;
                    if (x.getOrderItemId() != 0) {
                        orderItem = orderItemMapper.selectById(x.getOrderItemId());
                    }
                    //入库
                    goods.setGoodsNumber(goods.getGoodsNumber() + x.getGoodsNum());
                    if (orderItem != null) {
                        // logger.info("orderItem:{}", orderItem);
                        orderItem.setIsInto(1);
                        orderItem.setIsOut(1);
                        orderItemMapper.updateById(orderItem);
                    }

                    //对仓库商品进行修改 如果存在便添加商品,如果不存在就创建商品

                    if (x.getOweItem() == 0) {
                        intserOrUpdateWarehouseItem(item, x);
                        //欠货
                        oweGoodsByIn(orderItem, x, order, userId, goods.getSuppliersId());
                    } else {
                        ErpOweGoodsItem oweGoodsItem = erpOweGoodsItemMapper.selectById(x.getOweItem());
                        if (oweGoodsItem == null) {
                            throw new RuntimeException("没有发现这个欠货列");
                        }
                        if (oweGoodsItem.getNumber() >= x.getGoodsNum()) {
                            Preconditions.checkArgument(erpGoodService.replenishGoods(oweGoodsItem.getId(), x.getGoodsNum()), "还货失败!");
                            x.setDefaultMsg("还货-- 商品ID:" + x.getGoodsId()
                                    + " 还货数量:" + x.getGoodsNum() + " 欠货单号:" + oweGoodsItem.getOrderSn() + " 欠货ID:" + oweGoodsItem.getId());
                        } else {
                            Preconditions.checkArgument(erpGoodService.replenishGoods(oweGoodsItem.getId(), oweGoodsItem.getNumber()), "还货失败!");
                            x.setDefaultMsg("还货-- 商品ID:" + x.getGoodsId()
                                    + " 还货数量:" + x.getGoodsNum() + " 欠货单号:" + oweGoodsItem.getOrderSn() + " 欠货ID:" + oweGoodsItem.getId());
                        }
                        erpOrderItemMapper.updateById(x);
                        intserOrUpdateWarehouseItem(item, x);


                    }
                    erpGoodMapper.updateById(goods);
                }
            });

            if (!items.isEmpty()) {
                ErpOrderItem item = items.get(0);
                if (item.getOrderItemId() != 0) {
                    insertOutOrInOweGoods(item, userId, order.getMode());
                }
            }

            //本地订单不显示
            ErpRemoteOrder remoteOrder = erpRemoteOrderMapper.selectOneByOrderSn(order.getOriginOrderSn());
            if(remoteOrder != null) {
                remoteOrder.setStatus(1);
                if (!StringUtil.isNullOrEmpty(remoteOrder.getOriginOrder())) {
                    String poSn = orderMapper.selectSnPoByOrderSn(remoteOrder.getOriginOrder());
                    if(poSn != null){
                        orderItemMapper.updateOrderItemForOneByOrderSn(poSn);
                    }
                }
                erpRemoteOrderMapper.updateById(remoteOrder);
            }

            order.setStatus(ErpOrderStatus.pass.getStatus());
            //设置执行者姓名和执行时间.
            order.setExecuteTime(LocalDateTime.now());
            order.setExecutor(user.getUserName());
        } else {
            throw new RuntimeException("订单状态异常!");
        }
    }


    /**
     * 处理出库订单类型
     *
     * @param order
     * @param status
     * @param userId
     * @return
     */
    private void modeOut(final ErpOrder order, int status, int userId) {
        AdminUser user = adminUserMapper.selectById(userId);
        Preconditions.checkNotNull(user, "用户不存在。");
        //出库单操作
        if (status == ErpOrderStatus.draft.getStatus()) {
            //草稿状态 -- 提交申请

            order.setStatus(ErpOrderStatus.submit.getStatus());


        } else if (status == ErpOrderStatus.submit.getStatus()) {
            //财务审核到 -- 订单审核
            AdminUser store = adminUserMapper.selectById(order.getStoreId());
            ErpFinanceLog log = new ErpFinanceLog();
            log.setOrderNumber("SK" + Instant.now().toEpochMilli());
            log.setOrderSn(order.getOrderInfo());
            log.setChecktime(LocalDateTime.now());
            log.setTotal(erpOrderMapper.selectOrderTotal(order.getOrderId()));
            log.setStatus(ErpOrderStatus.submit.getStatus());
            log.setStoreName(store.getUserName());
            log.setMode(ErpFinanceLog.MODE_RECEIPT);
            //初始化反点金额
            BigDecimal rebateRate = store.getRebateRate();
            if (rebateRate == null || rebateRate.doubleValue() == 0.0) {
                rebateRate = BigDecimal.ZERO;
            }
            BigDecimal rebate = log.getSubTotal().multiply(rebateRate);
            log.setRebate(rebate);
            log.setUserBalance(store.getBalance());
            log.setCreater(user.getUserName());
            erpFinanceLogMapper.insert(log);
            order.setStatus(ErpOrderStatus.finance.getStatus());
        } else if (status == ErpOrderStatus.finance.getStatus()) {
            throw new RuntimeException("请在财务页面通过!");
        } else if (status == ErpOrderStatus.financeFinish.getStatus()) {


            //状态由带审核变成审核成功

            //提交申请 -- 通过
            //更新订单所有的数值
            QueryWrapper<ErpOrderItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.eq("order_id", order.getOrderId());
            List<ErpOrderItem> items = erpOrderItemMapper.selectList(itemWrapper);


            items.forEach((x) -> {
                ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
                if (goods != null) {
                    ErpWarehouseItem item = warehouseItemMapper.selectItemByGoodsIdAndWhId(x.getGoodsId(), x.getGoodsList());
                    logger.info("goods的ID:{} 名称:{} 数量:{} 待减数量:{} 缺货数量:{}",
                            goods.getGoodsId(), goods.getGoodsName(), goods.getGoodsNumber(), x.getGoodsNum(), x.getOweNum());
                    //根据订单的类型判断是添加还是删除
                    OrderItem orderItem = null;
                    if (x.getOrderItemId() != 0) {
                        orderItem = orderItemMapper.selectById(x.getOrderItemId());
                    }

                    //出库
                    if (x.getOweItem() != 0) {
                        //还货 要减库存
                        ErpOweGoodsItem oweGoodsItem = erpOweGoodsItemMapper.selectById(x.getOweItem());
                        if (oweGoodsItem == null) {
                            throw new RuntimeException("该商品{" + goods.getGoodsName() + "}没有缺货");
                        }
                        if (oweGoodsItem.getNumber() >= x.getGoodsNum()) {
                            x.setDefaultMsg("补货-- 商品ID:" + x.getGoodsId()
                                    + " 补货数量:" + x.getGoodsNum() + " 补货单号:" + oweGoodsItem.getOrderSn() + " 补货ID:" + oweGoodsItem.getId());
                            erpGoodService.replenishGoods(oweGoodsItem.getId(), x.getGoodsNum());
                        } else {
                            x.setDefaultMsg("补货-- 商品ID:" + x.getGoodsId()
                                    + " 补货数量:" + x.getGoodsNum() + " 补货单号:" + oweGoodsItem.getOrderSn() + " 补货ID:" + oweGoodsItem.getId());
                            erpGoodService.replenishGoods(oweGoodsItem.getId(), oweGoodsItem.getNumber());
                        }
                    }


                    if (x.getGoodsNum() != 0) {
                        if (item == null) {
                            throw new RuntimeException("货架ID:" + x.getGoodsList() + "上没有这个商品{" + goods.getGoodsName() + "}!");
                        } else {
                            if (x.getGoodsNum() > item.getStock()) {
                                throw new RuntimeException("货架ID:" + item.getWhId() + " 上的商品{" + goods.getGoodsName() + "}不够!");
                            }
                            item.setStock(item.getStock() - x.getGoodsNum());
                            warehouseItemMapper.updateById(item);
                        }
                        goods.setGoodsNumber(goods.getGoodsNumber() - x.getGoodsNum());
                    }

                    //缺货
                    if (x.getOweItem() == 0) {
                        oweGoodsByOut(orderItem, x, order, userId, goods.getSuppliersId());
                    }

                    //设置为以出库
                    outStatusChange(orderItem, order);
                    erpGoodMapper.updateById(goods);
                }
            });

            if (!items.isEmpty()) {
                ErpOrderItem item = items.get(0);
                if (item.getOrderItemId() != 0) {
                    insertOutOrInOweGoods(item, userId, order.getMode());
                }
            }

            //设置origin_order的订单状态
            if (!StringUtil.isNullOrEmpty(order.getOriginOrderSn())) {
                updateOrderStatus(order.getOriginOrderSn(), order.getOrderId());
            }


            order.setStatus(ErpOrderStatus.pass.getStatus());
            //设置执行者姓名和执行时间.
            order.setExecuteTime(LocalDateTime.now());
            order.setExecutor(user.getUserName());
        } else {
            throw new RuntimeException("订单状态异常!");
        }
    }

    private void modeOutOld(final ErpOrder order, int status, int userId) {
        //出库单操作
        if (status == ErpOrderStatus.draft.getStatus()) {
            //草稿状态 -- 提交申请

            order.setStatus(ErpOrderStatus.submit.getStatus());


        } else if (status == ErpOrderStatus.submit.getStatus()) {

            //状态由带审核变成审核成功
            AdminUser user = adminUserMapper.selectById(userId);
            Preconditions.checkNotNull(user, "用户不存在。");

            //提交申请 -- 通过
            //更新订单所有的数值
            QueryWrapper<ErpOrderItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.eq("order_id", order.getOrderId());
            List<ErpOrderItem> items = erpOrderItemMapper.selectList(itemWrapper);

            items.forEach((x) -> {
                ErpGoods goods = erpGoodMapper.selectById(x.getGoodsId());
                if (goods != null) {
                    ErpWarehouseItem item = warehouseItemMapper.selectItemByGoodsIdAndWhId(x.getGoodsId(), x.getGoodsList());
                    logger.info("goods的ID:{} 名称:{} 数量:{} 待减数量:{} 缺货数量:{}",
                            goods.getGoodsId(), goods.getGoodsName(), goods.getGoodsNumber(), x.getGoodsNum(), x.getOweNum());
                    //根据订单的类型判断是添加还是删除
                    OrderItem orderItem = null;
                    if (x.getOrderItemId() != 0) {
                        orderItem = orderItemMapper.selectById(x.getOrderItemId());
                    }
                    //出库
                    if (x.getOweItem() != 0) {
                        //还货 要减库存
                        ErpOweGoodsItem oweGoodsItem = erpOweGoodsItemMapper.selectById(x.getOweItem());
                        if (oweGoodsItem == null) {
                            throw new RuntimeException("没有发现这个缺货列");
                        }
                        if (oweGoodsItem.getNumber() >= x.getGoodsNum()) {
                            x.setDefaultMsg("补货-- 商品ID:" + x.getGoodsId()
                                    + " 补货数量:" + x.getGoodsNum() + " 补货单号:" + oweGoodsItem.getOrderSn() + " 补货ID:" + oweGoodsItem.getId());
                            erpGoodService.replenishGoods(oweGoodsItem.getId(), x.getGoodsNum());
                        } else {
                            x.setDefaultMsg("补货-- 商品ID:" + x.getGoodsId()
                                    + " 补货数量:" + x.getGoodsNum() + " 补货单号:" + oweGoodsItem.getOrderSn() + " 补货ID:" + oweGoodsItem.getId());
                            erpGoodService.replenishGoods(oweGoodsItem.getId(), oweGoodsItem.getNumber());
                        }
                    }


                    if (x.getGoodsNum() != 0) {
                        if (item == null) {
                            throw new RuntimeException("货架上没有这个商品!");
                        } else {
                            if (x.getGoodsNum() > item.getStock()) {
                                throw new RuntimeException("货架上的商品不够!");
                            }
                            item.setStock(item.getStock() - x.getGoodsNum());
                            warehouseItemMapper.updateById(item);
                        }
                        goods.setGoodsNumber(goods.getGoodsNumber() - x.getGoodsNum());
                    }

                    //缺货
                    if (x.getOweItem() == 0) {
                        oweGoodsByOut(orderItem, x, order, userId, goods.getSuppliersId());
                    }

                    //设置为以出库
                    outStatusChange(orderItem, order);
                    erpGoodMapper.updateById(goods);

                    //设置origin_order的订单状态
//                    if(!StringUtil.isNullOrEmpty(order.getOriginOrderSn())){
//                        updateOrderStatus(order.getOriginOrderSn());
//                    }

                }
            });

            if (!items.isEmpty()) {
                ErpOrderItem item = items.get(0);
                if (item.getOrderItemId() != 0) {
                    insertOutOrInOweGoods(item, userId, order.getMode());
                }
            }

            order.setStatus(ErpOrderStatus.pass.getStatus());
            //设置执行者姓名和执行时间.
            order.setExecuteTime(LocalDateTime.now());
            order.setExecutor(user.getUserName());
        } else {
            throw new RuntimeException("订单状态异常!");
        }
    }

    private void updateOrderStatus(String originOrderSn, int orderId) {
        int orderNum = Optional.ofNullable(orderItemMapper.selectOriginOrderNumber(originOrderSn)).orElse(0);
        int outOrderNum = Optional.ofNullable(
                orderItemMapper.selectOutOrderNumberByOrigin(originOrderSn,
                        orderId,
                        ErpOrderController.MODE_OUT,
                        ErpOrderStatus.pass.getStatus())).orElse(0);
        logger.info("出库数量:{} 原始数量:{}", outOrderNum, orderNum);
        if (outOrderNum >= orderNum) {
            //更新为已完成
            orderMapper.updateOrderStatus(originOrderSn, OrderStatus.completed.getStatus());
        } else {
            //更新为部分销售
            orderMapper.updateOrderStatus(originOrderSn, OrderStatus.partialSales.getStatus());
        }
    }

    private void insertOutOrInOweGoods(ErpOrderItem item, int userId, int mode) {
        if (item.getOrderItemId() == 0) {
            return;
        }
        String orderSn = orderItemMapper.selectOrderSn(item.getOrderItemId());
        List<OrderItem> items = orderItemMapper.selectIdsByNotOutAndIn(orderSn);
        if (!items.isEmpty()) {
            //ErpOweGoodsItem
            for (OrderItem orderItem : items) {
                ErpOweGoodsItem oweItem = new ErpOweGoodsItem();
                oweItem.setMode(mode);
                oweItem.setNumber(orderItem.getGoodsNum());
                oweItem.setGoodsId(orderItem.getGoodsId());
                oweItem.setSinglePrice(orderItem.getShopPrice());
                oweItem.setOrderSn(orderItem.getOrderSn());
                oweItem.setItemId(orderItem.getId());
                oweItem.setOweTime(LocalDateTime.now());
                oweItem.setUserId(userId);
                oweItem.setSupplierId(erpGoodMapper.selectSupplierById(orderItem.getGoodsId()));
                erpOweGoodsItemMapper.insert(oweItem);
                orderItem.setIsInto(1);
                orderItem.setIsOut(1);
                orderItemMapper.updateById(orderItem);
            }
        }
    }

    @Override
    public List<ErpOweItemList> getOweTtemListByMode(int mode) {
        Stopwatch watch = Stopwatch.createStarted();
        List<ErpOweItemList> list = getOweItemListByModeForFast(mode);
        watch.stop();
        logger.info("欠缺货列表耗时:{}", watch.toString());
        // 欠货耗时： 8.418 s  -- 4.338s
        // 缺货耗时: 3.581 s   -- 1.546s

        return list;
    }


    public List<ErpOweItemList> getOweItemListByModeForFast(int mode) {
        // 欠货耗时： 8.418 s  -- 4.338s
        // 缺货耗时: 3.581 s   -- 1.546s
        List<ErpOweItemList> list = new ArrayList<>();
        List<String> orders = erpOweGoodsItemMapper.getOrderSnsByMode(mode);
        for (String order : orders) {
            ErpOweItemList oweItemList = new ErpOweItemList();
            oweItemList.setOrderSn(order);
            AdminUser adminUser = adminUserMapper.selectUserByOrderSn(order);
            oweItemList.setAdminUser(adminUser);
            oweItemList.setItems(getOweTempOrder(order, mode));
            //默认注解
            oweItemList.setComment(orderMapper.selectOrderContext(oweItemList.getOrderSn()));
            list.add(oweItemList);
        }
        return list;
    }

    @Override
    public List<ErpTempOrderItem> getOweTempOrder(String orderSn, int mode) {
        QueryWrapper<ErpOweGoodsItem> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("order_sn", orderSn)
                .eq("mode", mode).ne("number", 0);
        List<ErpOweGoodsItem> erpOweGoodsItems = erpOweGoodsItemMapper.selectList(itemQueryWrapper);
        List<ErpTempOrderItem> tempOrderItems = new ArrayList<>(erpOweGoodsItems.size());
        if (erpOweGoodsItems.isEmpty()) {
            return new ArrayList<>();
        }

        Integer index = orderItemMapper.selectMinId(orderSn);
        int modeType = 0;
        for (ErpOweGoodsItem item : erpOweGoodsItems) {
            ErpGoods goods = erpGoodMapper.selectById(item.getGoodsId());
            if (goods != null) {
                tempOrderItems.add(oweItem2TempItem(item, goods, index - 1, modeType));

            }
        }
        return tempOrderItems;
    }

    @Override
    public ErpTempOrderItem oweItem2TempItem(final ErpOweGoodsItem x, final ErpGoods goods, int index, int modeType) {
        ErpTempOrderItem orderItem = new ErpTempOrderItem();

        ErpWarehouse warehouse = erpWarehouseMapper.selectDefaultWarehouseByGoodsId(x.getGoodsId());
        orderItem.setGoodsId(x.getGoodsId());
        if (warehouse != null) {
            orderItem.setGoodsList(warehouse.getId());
            orderItem.setGoodsListName(warehouse.getWarehouseName());
            orderItem.setDefaultWarehouse(warehouse);
        } else {
            orderItem.setGoodsList(0);
            orderItem.setGoodsListName("");
        }

        Brand brand = brandMapper.selectById(goods.getBrandId());
        orderItem.setGoodsName(goods.getGoodsName());
        orderItem.setGoodsNum(x.getNumber());
        orderItem.setGoodsPrice(x.getSinglePrice());
        orderItem.setBrandName(brand.getBrandName());
        orderItem.setGoodsDesc(goods.getGoodsDesc());
        orderItem.setStock(goods.getGoodsNumber());
        orderItem.setPAddress(goods.getPAddress());
        orderItem.setSupplier(supplierMapper.selectById(goods.getSuppliersId()));
        orderItem.setNumberUnit(String.valueOf(goods.getNumberUnit()));
        orderItem.setSpecifications(goods.getSpecifications());
        orderItem.setOweItem(x.getId());
        orderItem.setStock(goods.getGoodsNumber());
        orderItem.setOrderItemId(x.getItemId());
        Integer centralized = Optional.ofNullable(brandMapper.selectCentralizedPurchasing(brand.getBrandName())).orElse(0);
        orderItem.setCentralizedPurchasing(centralized);
        ErpCategory category = erpCategoryMapper.selectById(goods.getCatId());
        if (category != null) {
            orderItem.setGoodsUnit(category.getMeasureUnit());
        }
        //小单位
        SmallUnit smallUnit = smallUnitMapper.selectById(goods.getSmallunitId());
        if (smallUnit == null) {
            orderItem.setGoodsUnit("件");
        } else {
            orderItem.setGoodsUnit(smallUnit.getName());
        }

        orderItem.setIndex(x.getItemId() - index);

        return orderItem;
    }

    /**
     * 设置x的orderItem为以出库状态
     */
    @Override
    public void outStatusChange(OrderItem orderItem, ErpOrder order) {
        if (orderItem != null && order.getMode() == ErpOrderController.MODE_OUT) {
            orderItem.setIsOut(1);
            orderItem.setIsInto(1);
            orderItemMapper.updateById(orderItem);
        }
    }


    @Override
    public void oweGoodsByIn(OrderItem orderItem, ErpOrderItem x, ErpOrder order, int userId, int supplierId) {
        if (x.getOrderItemId() != 0) {
            if (orderItem != null && order.getMode() == ErpOrderController.MODE_IN) {
                ErpOweGoodsItem oweGoodsItem = new ErpOweGoodsItem();
                oweGoodsItem.setGoodsId(x.getGoodsId());
                oweGoodsItem.setItemId(orderItem.getId());
                oweGoodsItem.setMode(0);
                oweGoodsItem.setNumber(x.getOweNum());
                oweGoodsItem.setOrderSn(orderItem.getOrderSn());
                oweGoodsItem.setOweTime(LocalDateTime.now());
                oweGoodsItem.setSinglePrice(x.getGoodsPrice());
                oweGoodsItem.setUserId(userId);
                oweGoodsItem.setSupplierId(supplierId);
                //   logger.info("添加欠缺货数据:{}", oweGoodsItem);
                if (x.getOweNum() > 0) {
                    erpOweGoodsItemMapper.insert(oweGoodsItem);
                }
            }
        }
    }

    /**
     * 缺货功能  /出库
     * 缺货不会直接减去数据库里的商品但是会记录下来.
     *
     * @param x     erpOrderItem
     * @param order erpOrder
     */
    @Override
    public void oweGoodsByOut(OrderItem orderItem, ErpOrderItem x, ErpOrder order, int userId, int supplierId) {
        if (x.getOrderItemId() != 0) {
            if (orderItem != null && order.getMode() == ErpOrderController.MODE_OUT) {
                ErpOweGoodsItem oweGoodsItem = new ErpOweGoodsItem();
                oweGoodsItem.setGoodsId(x.getGoodsId());
                oweGoodsItem.setItemId(orderItem.getId());
                oweGoodsItem.setMode(1);
                int oweNumber = orderItem.getGoodsNum() - x.getGoodsNum();
                if (oweNumber > 0) {
                    oweGoodsItem.setNumber(oweNumber);
                    x.setOweNum(oweNumber);
                    oweGoodsItem.setOrderSn(orderItem.getOrderSn());
                    oweGoodsItem.setOweTime(LocalDateTime.now());
                    oweGoodsItem.setSinglePrice(x.getGoodsPrice());
                    oweGoodsItem.setUserId(userId);
                    oweGoodsItem.setSupplierId(supplierId);
                    logger.info("添加欠缺货数据:{}", oweGoodsItem);
                    erpOweGoodsItemMapper.insert(oweGoodsItem);
                }
            }
        }
    }


    /**
     * 对仓库商品进行修改 如果存在便添加商品,如果不存在就创建商品
     *
     * @param item
     * @param x
     */
    @Override
    public void intserOrUpdateWarehouseItem(ErpWarehouseItem item, ErpOrderItem x) {
        if (item == null) {
            item = new ErpWarehouseItem();
            item.setGoodsId(x.getGoodsId());
            item.setWhId(x.getGoodsList());
            item.setStock(x.getGoodsNum());
            warehouseItemMapper.insert(item);
        } else {
            item.setStock(item.getStock() + x.getGoodsNum());
            warehouseItemMapper.updateById(item);
        }
    }


    private void warehouseItemFor(ErpWarehouseItem item, ErpOrderItem x, int number, int mode) {
        if (item == null) {
            item = new ErpWarehouseItem();
            item.setGoodsId(x.getGoodsId());
            item.setWhId(x.getGoodsList());
            if (mode == 0) {
                item.setStock(number);
            } else {
                item.setStock(0);
            }
            warehouseItemMapper.insert(item);
        } else {
            if (mode == 0) {
                item.setStock(item.getStock() + number);
            } else {
                item.setStock(item.getStock() - number);
            }
            warehouseItemMapper.updateById(item);
        }
    }

    @Override
    public boolean deleteErpOrder(String orderSn) {
        if (erpOrderMapper.deleteByOrderSn(orderSn)) {
            erpOrderItemMapper.deleteItemsByOrderSn(orderSn);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean endedOwe(String orderSn) {
        //生成一个退款单 TK,与CGDD单号管理,状态为2(已完成)

        ErpOrder order = new ErpOrder();
        order.setOriginOrderSn(orderSn);
        order.setStatus(ErpOrderStatus.pass.getStatus());
        order.setOrderInfo("TK" + Instant.now().toEpochMilli());
        order.setCreateTime(LocalDateTime.now());
        order.setExecuteTime(LocalDateTime.now());
        order.setMode(2);

        if (erpOrderMapper.insert(order) == 1) {
            List<ErpOweGoodsItem> oweGoodsItems = erpOweGoodsItemMapper.selectListByOrderSn(orderSn);
            for (ErpOweGoodsItem oweGoodsItem : oweGoodsItems) {
                ErpOrderItem erpOrderItem = new ErpOrderItem();
                erpOrderItem.setOrderSn(order.getOrderInfo());
                erpOrderItem.setGoodsNum(oweGoodsItem.getNumber());
                erpOrderItem.setGoodsPrice(oweGoodsItem.getSinglePrice());
                erpOrderItemMapper.insert(erpOrderItem);
            }
        } else {
            throw new RuntimeException("生成退款单失败!");
        }

        //出库单终结
        return erpOweGoodsItemMapper.changeOrderSnToEnded(orderSn);
    }


    @Override
    public boolean rkBack(String orderSn) {
        ErpOrder order = erpOrderMapper.selectErpOrderByOrderSn(orderSn);
        if (order == null) {
            throw new RuntimeException("不存在此订单");
        }
        if (order.getStatus() != ErpOrderStatus.pass.getStatus()) {
            throw new RuntimeException("只支持完成的出库单回滚!");
        }
        if (order.getMode() != ErpOrderController.MODE_IN) {
            throw new RuntimeException("订单不是入库单");
        }
        List<ErpOrderItem> orderItems = erpOrderItemMapper.selectOrderItemsByOrderId(order.getOrderId());
        for (ErpOrderItem item : orderItems) {
            orderItemRecovery(item);
        }
        order.setStatus(ErpOrderStatus.draft.getStatus());
        return erpOrderMapper.updateById(order) == 1;
    }

    @Transactional
    public void orderItemRecovery(ErpOrderItem item) {
        if (item.getOrderItemId() != 0) {
            orderItemMapper.setOrderIntoAndOutForZero(item.getOrderItemId());
        }
        if (item.getOweItem() > 0) {
            //删除欠货单..
            erpOweGoodsItemMapper.deleteByItemId(item.getOrderItemId());
        }
        if (!warehouseItemMapper.subGoodsNumber(item.getGoodsId(), item.getGoodsList(), item.getGoodsNum())) {
            throw new RuntimeException(item.getGoodsName() + " 商品库位异常!");
        }
        erpGoodMapper.subGoodsNum(item.getGoodsId(), item.getGoodsNum());
    }


    @Override
    public List<Order> remoteOrders(AdminUser user) {

        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("notin", JSONArray.toJSONString(erpRemoteOrderMapper.selectRemoteOrder()));
        requestBody.add("userName", user.getUserName());
        logger.info("请求的数据: {}", requestBody);
        RestTemplate restTemplate = new RestTemplate();
        Result response =
                restTemplate.postForObject(remoteUrl + "/erp-order/remote-out", requestBody, Result.class);
        if (response.getCode() != 200) {
            throw new RuntimeException(response.getMsg());
        }
        ErpWarehouse warehouse = erpWarehouseMapper.selectDefaultOne();
        List<Order> orders = JSONArray.parseArray(response.getData().toString(), Order.class);
        for (Order order : orders) {
            List<ErpTempOrderItem> newItem = new ArrayList<>();
            order.getItems().forEach((x) -> {
                Integer id = erpGoodMapper.selectGoodsId(x.getGoodsSn());
                if (id != null) {
                    x.setGoodsId(id);
                    x.setDefaultWarehouse(warehouse);
                    x.setGoodsListName(warehouse.getWarehouseName());
                    x.setGoodsList(warehouse.getId());
                    newItem.add(x);
                }
            });
            order.setItems(newItem);
        }
        return orders.stream().filter(x -> {
            return !x.getItems().isEmpty();
        }).collect(Collectors.toList());
    }
}
